package com.ikdong.toodle.widget;

import java.util.ArrayList;
import java.util.List;

import com.ikdong.toodle.activity.TaskListActivity;
import com.ikdong.toodle.model.Task;
import com.ikdong.toodle.util.Constant;
import com.ikdong.toodle.util.TaskManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;

public class TaskTabAdapter extends FragmentStatePagerAdapter {
	protected String[] tabs;
	protected String type;
	protected TaskManager manager;
	protected List<Task> tasks = new ArrayList<Task>();
	protected List<TaskTabFragment> framents = new ArrayList<TaskTabFragment>();
	protected SparseArray<View> views = new SparseArray<View>();
	private SharedPreferences sp;

	public TaskTabAdapter(FragmentManager fm,Context context,String[] tabs,String type) {
		super(fm);
		manager = new TaskManager(context);
		sp = context.getSharedPreferences(Constant.CONFIG_FILE, 0);
		String sortItem = sp.getString(TaskListActivity.SORT_ITEM, TaskListActivity.SORT_DATE_ADD);
		long sortBy = sp.getLong(TaskListActivity.SORT_BY, TaskListActivity.SORT_BY_RESERVES);
		tasks.addAll(manager.get(sortItem,sortBy));
		this.tabs = tabs;
		this.type = type;
		initFraments();
	}

	@Override
    public Fragment getItem(int position) {
		return framents.get(position);
    }
	
    @Override
    public CharSequence getPageTitle(int position) {
    	String title = tabs[position];
        return title;
    }

    @Override
    public int getCount() {
      return tabs.length;
    }
    
    public void initFraments(){
    	framents.clear();
    	for(String tab : tabs){
    		Log.d("Tab", tab);
    		framents.add(TaskTabFragment.newInstance(this,tab,tasks,type));
    	}
    }
    
    public void changeView(String[] tabs){
    	this.tabs = tabs;
    	initFraments();
    }
    
    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }
    
    public void allDataChanged(){
    	for(TaskTabFragment f : framents){
    		if(f.getAdapter()!=null)
    			f.getAdapter().notifyDataSetChanged();
    	}
    }
    
    public void allDataChanged(long id){
    	for(TaskTabFragment f : framents){
    		if(f.getAdapter()!=null){
        		f.getAdapter().removeItem(id);
        		f.getAdapter().notifyDataSetChanged();
    		}
    	}
    }
}
